<template>
  <div>
    <div>
      <el-input v-model="input" style="width: 400px"></el-input>
      <el-button @click="encrypt">加密</el-button>
      <p>{{ jiami }}</p>
    </div>
    <div>
      <el-input v-model="input1" style="width: 490px"></el-input>
      <el-button @click="decrypt">解密</el-button>
      <p>{{ jiemi }}</p>
    </div>
  </div>
</template>

<script>
// import { Buffer } from "buffer";
import crypto from "crypto";
const keyStr = "12cf3a619cbb468c";
export default {
  name: "test",
  data() {
    return {
      input: "fIOSS#7777",
      input1: "xW90gVSEygriEeH4U5wIQTOsAk6UpV1T4LhSndZC1zAhSKAE3Rc=",
      jiemi: "请解密",
      jiami: "请加密",
    };
  },
  methods: {
    encrypt(word) {
      word = this.input;
      const iv = crypto.randomBytes(12);
      const cipher = crypto.createCipheriv("aes-128-gcm", keyStr, iv);
      const encrypted = cipher.update(word, "utf8");
      const end = cipher.final();
      const tag = cipher.getAuthTag();
      const res = Buffer.concat([iv, encrypted, end, tag]);
      const result = res.toString("base64");
      console.log(res,iv, encrypted, end, tag);
      this.jiami = result;
      return result;
    },
    decrypt(data) {
      data = this.input1;
      var bData = Buffer.from(data, "base64");
      const iv = bData.slice(0, 12);
      const tag = bData.slice(-16);
      const cdata = bData.slice(12, bData.length - 16);
      console.log(iv, tag, cdata, bData, data);
      const decipher = crypto.createDecipheriv("aes-128-gcm", keyStr, iv);
      decipher.setAuthTag(tag);
      var msg = decipher.update(cdata, "base64", "utf-8");
      console.log(decipher);
      const fin = decipher.final();
      console.log(fin);

      const decryptedStr = new TextDecoder("utf8").decode(
        Buffer.concat([msg, fin])
      );
      this.jiemi = decryptedStr;
      return decryptedStr;
    },

    _base64ToArrayBuffer(base64) {
      var binary_string = window.atob(base64); //解码使用base64编码的字符串
      var len = binary_string.length; //获取长度
      var bytes = new Uint8Array(len);
      for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
      }
      return bytes.buffer;
    },
    ab2str(buf) {
      return String.fromCharCode.apply(null, new Uint8Array(buf));
      // return buf;
    },
  },
  mounted() {},
};
</script>
<style>
</style>
